package com.hmall.item.service.impl;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.pojo.Item;
import com.hmall.item.pojo.RequestParams;
import com.hmall.item.pojo.SearchResponse;
import com.hmall.item.service.IItemService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class ItemService extends ServiceImpl<ItemMapper, Item> implements IItemService {
    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public PageDTO getlist(Integer page, Integer size) {
        Page<Item> page1 = new Page<>(page,size);
        Page<Item> itemPage = itemMapper.selectPage(page1, null);
        long total = itemPage.getTotal();
        List<Item> list = itemPage.getRecords();
        PageDTO<Item> pageDTO = new PageDTO<>(total, list);
        return pageDTO;
    }

    @Override
    public void addItem(Item item) {
        itemMapper.insert(item);
    }

    @Override
    public void onOrOff(Long id, Integer status) {
        this.lambdaUpdate().set(Item::getStatus,status)
                .eq(Item::getId,id).update();
    }

    @Override
    public void update1(Item item) {
        Item item1 = itemMapper.selectById(item.getId());
        if(item1.getStatus()==1){
            throw new RuntimeException("商品上架中，不能进行修改");
        }
        this.lambdaUpdate().update(item);
    }

    @Override
    public void deleteById(Long id) {
        Item item = itemMapper.selectById(id);
        if(item.getStatus()==1){
            throw new RuntimeException("商品上架中，不可被删除");
        }
        itemMapper.deleteById(id);
    }

    @Override
    public JSON filter(RequestParams item) {
        LambdaQueryWrapper<Item> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Item::getCategory,Item::getBrand)
                .eq(StringUtils.isNotBlank(item.getCategory()),Item::getCategory,item.getCategory());
//                .eq(StringUtils.isNotBlank(item.getBrand()),Item::getBrand,item.getBrand());
        List<Item> items = itemMapper.selectList(queryWrapper);
        Set<String> category1 = new HashSet<>();
        Set<String> brand1 = new HashSet<>();
        if(item.getCategory()==null){
            for (Item item1 : items) {
                category1.add(item1.getCategory());
                brand1.add(item1.getBrand());
            }
            String[] category = category1.toArray(new String[category1.size()]);
            String[] brand = brand1.toArray(new String[brand1.size()]);
            SearchResponse searchResponse = new SearchResponse(category, brand);
            return JSONUtil.parse(searchResponse);
        }else {
            for (Item item1 : items) {
                brand1.add(item1.getBrand());
            }
            String[] category = category1.toArray(new String[category1.size()]);
            String[] brand = brand1.toArray(new String[brand1.size()]);
            SearchResponse searchResponse = new SearchResponse(category, brand);
            return JSONUtil.parse(searchResponse);
        }
    }

    @Override
    public PageDTO list1(RequestParams requestParams) {
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(requestParams.getKeys()),"name",requestParams.getKeys())
                .orderByAsc(StringUtils.isNotBlank(requestParams.getSortBy()),requestParams.getSortBy())
                .eq(StringUtils.isNotBlank(requestParams.getCategory()),"category",requestParams.getCategory())
                .eq(StringUtils.isNotBlank(requestParams.getBrand()),"brand",requestParams.getBrand())
                .ge((requestParams.getMinPrice()!=null),"price",requestParams.getMinPrice())
                .le((requestParams.getMaxPrice()!=null),"price",requestParams.getMaxPrice())
                .eq("status",1);
        Page<Item> page = new Page<>(requestParams.getPage(),requestParams.getSize());
        Page<Item> itemPage = itemMapper.selectPage(page, queryWrapper);
        long total = itemPage.getTotal();
        List<Item> list = itemPage.getRecords();
        PageDTO<Item> pageDTO = new PageDTO<>(total, list);
        return pageDTO;
    }


    //缓存top20商品数据
    public void  getTop20(){
        String key = "top";
        redisTemplate.delete(key);
        RequestParams requestParams = new RequestParams();
        requestParams.setPage(1);
        requestParams.setSortBy("sold");
        requestParams.setSize(20);
        PageDTO pageDTO = list1(requestParams);
        redisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(pageDTO));
    }

    @Override
    public void changes(Long itemId, Integer num) {
        Item item = itemMapper.selectById(itemId);
        Integer sold = item.getSold();
        Integer stock = item.getStock();
        item.setStock(stock-num);
        item.setSold(sold+num);
        itemMapper.updateById(item);
    }

    @Override
    public void changes1(Long itemId, Integer num) {
        Item item = itemMapper.selectById(itemId);
        Integer sold = item.getSold();
        Integer stock = item.getStock();
        item.setStock(stock+num);
        item.setSold(sold-num);
        itemMapper.updateById(item);

    }


}
